package com.xxx.yuedong.community.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.xxx.yuedong.common.R;
import com.xxx.yuedong.common.consts.ActionConstants;
import com.xxx.yuedong.community.controller.form.DeleteAnnounceByIdForm;
import com.xxx.yuedong.community.controller.form.InsertAnnounceForm;
import com.xxx.yuedong.community.controller.form.SearchAllAnnounceForm;
import com.xxx.yuedong.community.controller.form.SearchAnnounceByIdForm;
import com.xxx.yuedong.community.pojo.Announce;
import com.xxx.yuedong.community.service.AnnounceService;
import com.xxx.yuedong.utils.EventMsgSendUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author HG
 * @version 1.0
 **/
@Api(tags = "公告相关接口")
@RestController
@RequestMapping("/announce")
public class AnnounceController {
    @Autowired
    private AnnounceService announceService;

    @PostMapping("/insert")
    @ApiOperation("发布公告")
    public R inset(@Valid @RequestBody InsertAnnounceForm form) {
        Announce announce = JSONUtil.parse(form).toBean(Announce.class);
        announce.setSenderId(StpUtil.getLoginIdAsLong());
        announce.setCreateTime(new Date());
        int rows = announceService.insert(announce);

        //向所有用户发送公告
        EventMsgSendUtil.sendEventMsg(StpUtil.getLoginIdAsLong(), announce.getId(), ActionConstants.ANNOUNCE);

        return R.ok().put("rows", rows);
    }

    @PostMapping("/deleteById")
    @ApiOperation("删除公告")
    public R deleteById(@RequestBody DeleteAnnounceByIdForm form) {
        int rows = announceService.deleteById(form.getIds());
        return R.ok().put("rows", rows);
    }

    @PostMapping("/searchAnnounceById")
    @ApiOperation("根据ID查询公告")
    public R searchAnnounceById(@RequestBody SearchAnnounceByIdForm form) {
        HashMap announce = announceService.searchAnnounceById(form.getId());
        return R.ok().put("announce", announce);
    }

    @PostMapping("/searchAllAnnounce")
    @ApiOperation("分页查询所有公告")
    public R searchAllAnnounce(@Valid @RequestBody SearchAllAnnounceForm form) {
        R r = announceService.searchAllAnnounce(form.getPage(), form.getPageSize(), form.getTitle());
        return r;
    }
}
